package youtube;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
 * this class get youtube views, likes and dislikes counts of a movie trailer
 * @author chenji
 *
 */
public class Youtube {
	public static String getInfo(String url) throws Exception {
		String view = "0", like = "0", dislike = "0";
		Document doc = Jsoup.connect(url).timeout(60 * 1000).get();
		Element div, span;
		if (!doc.select("div.watch-view-count").isEmpty()) {
			div = doc.select("div.watch-view-count").first();
			view = div.text();
		}
		if (!doc.select("span#watch-like-dislike-buttons").isEmpty()) {
			span = doc.select("span#watch-like-dislike-buttons").first();
			like = span.select("button").first().text();
			dislike = span.select("button").last().text();
			//System.out.println(span.text());
		}

		view = view.isEmpty() ? "0" : view;
		like = like.isEmpty() ? "0" : like;
		dislike = dislike.isEmpty() ? "0" : dislike;
		//System.out.println(view);
		//System.out.println(like + " " + dislike);
		int l = Integer.parseInt(like.replaceAll(",", ""));
		int d = Integer.parseInt(dislike.replaceAll(",", ""));
		return ",\"" + view + "\",\"" + like + "\",\"" + dislike + "\",\"" + (l+1) / (d+1) + "\"";
	}

	public static void main(String[] args) {
		try {
			getInfo("https://www.youtube.com/watch?v=XfRY0ASZHuU");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
